<template>
  <div>
    <el-dialog :title="userDetail.id?'编辑员工':'新增员工'" :visible="dialogFormVisible" @close="closeFn">
      <el-form ref="form" :model="userDetail" :rules="userRules">
        <el-form-item label="姓名" label-width="50px" prop="username">
          <el-input v-model="userDetail.username" />
        </el-form-item>
        <el-form-item label="邮箱" label-width="50px" prop="email">
          <el-input v-model="userDetail.email" />
        </el-form-item>
        <el-form-item label="密码" label-width="50px" prop="password">
          <el-input v-model="userDetail.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnFn">确 定</el-button>
        <el-button @click="closeFn">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { addUserRegister, editUserRegister } from '@/api/employees'
export default {
  data() {
    // 邮箱校验规则
    const checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (value && !reg.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false, // 显示新增和编辑员工弹窗
      userDetail: { // 填写的员工数据
        username: '',
        email: '',
        password: ''
      },
      userRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱地址错误', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 3, max: 16, message: '密码为3-16位字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 确认按钮触发的函数
    async btnFn() {
      try {
        await this.$refs.form.validate()
        //   console.log(1)
        // 确认提交数据
        // 判断如果有id就是编辑，没有就是新增
        if (this.userDetail.id) {
          await editUserRegister(this.userDetail)
          this.$emit('editBtnFn')
          this.$message.success('编辑员工成功')
        } else {
          await addUserRegister(this.userDetail)
          this.$emit('addBtnFn')
          // this.$message.success('新增员工成功')
        }
        this.closeFn()
      } catch (error) {
        // console.log(error)
      }
    },
    // 关闭窗口，数据清空
    closeFn() {
      this.userDetail = {
        username: '',
        email: '',
        password: ''
      }
      this.dialogFormVisible = false

      // 清空校验规则
      this.$refs.form.resetFields()
      // console.log(this.$refs.form)
    }
  }

}
</script>

<style>

</style>
